package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.model.MediaUploadResult;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.model.YgVote;
import com.ygqh.baby.po.YgVoteWork;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.SmsService;
import com.ygqh.baby.service.WeixinMaterialService;
import com.ygqh.baby.service.YgVoteWorkService;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.commons.lang.StringUtils;
import org.crazycake.shiro.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: sunshuo
 * @date: 2018/12/26 12:59
 */
@Controller
@RequestMapping("admin/vote")
public class VoteController extends BaseController {

    @Autowired
    private YgVoteWorkService ygVoteWorkService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private SmsService smsService;
    @Autowired
    private WeixinMaterialService weixinMaterialService;

    /**
     * 作品列表
     *
     * @param queryInfo   分页
     * @param nickName    用户名
     * @param checkStatus 审核状态
     * @return
     */
    @RequestMapping("searchVoteWork")
    @ResponseBody
    public Map<String, Object> searchVoteWork(QueryInfo queryInfo, String nickName, CheckStatus checkStatus) {
        YgVote voteInfo = ygVoteWorkService.getVoteInfoFromRedis();
        String voteBatchCode = null;
        if (voteInfo != null) {
            voteBatchCode = voteInfo.getVoteBatchCode();
        }
        ResultSet<YgVoteWork> resultSet = ygVoteWorkService.search(queryInfo, nickName, voteBatchCode, checkStatus);
        return resultSet.toDatatables(null);
    }

    /**
     * 更新作品审核状态
     *
     * @param id          id
     * @param checkStatus 审核状态
     * @return
     */
    @RequestMapping("updateWorkCheckStatus")
    @ResponseBody
    public Message updateWorkCheckStatus(@RequestParam Long id, @RequestParam(defaultValue = "Pass") CheckStatus checkStatus) {
        YgVoteWork voteWorkFromDb = ygVoteWorkService.findById(id);
        if (voteWorkFromDb == null) {
            return Message.error("作品不存在", null);
        }
        if (checkStatus.equals(voteWorkFromDb.getCheckStatus())) {
            return Message.error("作品已" + checkStatus.getTitle(), null);
        }
        YgVoteWork voteWork = new YgVoteWork();
        voteWork.setId(id);
        voteWork.setCheckStatus(checkStatus);
        voteWork.setUpdateBy(getSession().getTrueName());
        voteWork.setUpdateTime(new Date());
        ygVoteWorkService.update(voteWork);

        if (YgStringUtils.isChinaPhoneLegal(voteWorkFromDb.getUserName())) {
            if (CheckStatus.Pass.equals(checkStatus)) {
                smsService.sendSms(voteWorkFromDb.getUserName(), "您的晒娃作品已经审核通过，请到壹果微信公众号，点击底部 限时活动 晒娃 菜单 进行拉票");
            } else if (CheckStatus.Reject.equals(checkStatus)) {
                smsService.sendSms(voteWorkFromDb.getUserName(), "您的晒娃作品审核未通过，请到壹果微信公众号，点击底部 限时活动 晒娃 菜单 进行重新报名");
            }
        }
        return Message.success(null);
    }

    @RequestMapping("deleteVoteWork")
    @ResponseBody
    public Message deleteVoteWork(@RequestParam Long id) {
        YgVoteWork voteWork = new YgVoteWork();
        voteWork.setId(id);
        voteWork.setStatus(DataStatus.Delete);
        voteWork.setUpdateBy(getSession().getTrueName());
        voteWork.setUpdateTime(new Date());
        ygVoteWorkService.update(voteWork);
        return Message.success(null);
    }

    /**
     * 设置投票活动信息
     *
     * @param voteInfo 活动信息
     * @return
     */
    @RequestMapping("setVoteInfo")
    @ResponseBody
    public Message setVoteInfo(@RequestParam String voteInfo) {
        if (StringUtils.isBlank(voteInfo)) {
            return Message.error("投票活动信息不能为空", null);
        }
        YgVote ygVote = JSON.parseObject(voteInfo, YgVote.class);
        ygVote.setUpdateBy(getSession().getTrueName());
        ygVote.setUpdateTime(new Date());
        YgVote voteInfoFromRedis = ygVoteWorkService.getVoteInfoFromRedis();
        if (voteInfoFromRedis != null) {
            ygVote.setCreateBy(voteInfoFromRedis.getCreateBy());
            ygVote.setCreateTime(voteInfoFromRedis.getCreateTime());
        } else {
            ygVote.setCreateBy(ygVote.getUpdateBy());
            ygVote.setCreateTime(ygVote.getUpdateTime());
        }
        redisDao.set(RedisConstant.VOTE_BASE_INFO, JSON.toJSONString(ygVote), 0);
        return Message.success(null);
    }

    /**
     * 投票活动信息
     *
     * @return
     */
    @RequestMapping("getVoteInfo")
    @ResponseBody
    public Message getVoteInfo() {
        return Message.success(ygVoteWorkService.getVoteInfoFromRedis());
    }

    /**
     * 上传妈妈群二维码到素材
     *
     * @param qrcodes 妈妈群二维码
     * @return
     */
    @SuppressWarnings({"unchecked"})
    @RequestMapping("setYgMotherQrcodeMedia")
    @ResponseBody
    public Message setYgMotherQrcodeMedia(@RequestParam String qrcodes) {
        byte[] bytes = redisDao.get(RedisConstant.YIIGOO_MOTHER_GROUP_QRCODE.getBytes());
        if (bytes != null && bytes.length > 0) {
            List<String> list = (List<String>) SerializeUtils.deserialize(bytes);
            list.forEach(mediaId -> {
                try {
                    weixinMaterialService.deleteMaterial(mediaId);
                } catch (WeixinException e) {
                    logger.error("删除公众号永久素材异常，" + e.getErrorMsg(), e);
                }
            });
        }
        String[] split = qrcodes.split(",");
        List<String> errUp = new ArrayList<>();
        List<String> mediaIdList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            if (StringUtils.isBlank(split[i])) {
                continue;
            }
            try {
                MediaUploadResult result = weixinMaterialService
                        .addImageMaterial(true, split[i], "壹果妈妈群_" + (i + 1) + ".jpg");
                mediaIdList.add(result.getMediaId());
            } catch (WeixinException e) {
                logger.error("新增公众号永久素材异常，" + e.getErrorMsg(), e);
                errUp.add(split[i]);
            }
        }
        if (mediaIdList.size() > 0) {
            redisDao.set(RedisConstant.YIIGOO_MOTHER_GROUP_QRCODE.getBytes(),
                    SerializeUtils.serialize(mediaIdList), 0);
        }
        if (errUp.size() > 0) {
            return Message.error("部分图片上传失败，errQrcode=" + errUp, mediaIdList);
        }
        return Message.success(mediaIdList);
    }
}
